<template>
  <div id="dymamicTable">
    <vxe-table
      ref="xTable"
      v-loading="tableLoading"
      :data="tableData"
      :footer-method="footerMethod"
      :footer-cell-class-name="footerCellClassName"
      show-footer
      border
      resizable
      show-overflow
      keep-source
      round
      :height="height"
      highlight-hover-row
      :checkbox-config="{ highlight: true}"
      :header-cell-style="{
        'background-color': 'rgb(64, 158, 255)',
        'color':'#fff',
        'border-bottom': '1px solid #fff',
        'text-align': 'center',
        'border-right': '1px solid #fff',
      }"
      :cell-style="cellStyle"
    >
      <!--模版  -->
      <template v-for="item in tableHeader">
        <!-- 有多级表头 -->
        <!-- Math.random 用于解决表格之间相互切换所产生的一系列问题 -->
        <table-column
          v-if="item.children && item.children.length>0"
          :key="item.id+''"
          :coloumn-header="item"
          show-overflow-tooltip
        />
        <!-- 一级表头 -->
        <template v-else>
          <vxe-table-column
            :key="item.id+Math.random()+''"
            :field="item.value"
            :title="item.label"
            :fixed="getFixed(item)"
            show-overflow-tooltip
            :min-width="getColumnWidth(item)"
            type="html"
            :edit-render="{name: 'input', attrs: {disabled: nameDisabled}}"
          />
        </template>
      </template>
      <vxe-table-column v-if="showDetailView()" field="do" fixed="right" title="操作" width="160">
        <template v-slot="{ row }">
          <span class="view-click" @click="viewClick(row)">查看明细</span>
        </template>
      </vxe-table-column>
    </vxe-table>
  </div>
</template>
<script>
import tableColumn from '../TableColumn/index';
import commonVariable from '@/utils/commonVariable';
import XEUtils from 'xe-utils';
import { expandColunms, showDetailViewArr } from '@/views/reportCenter/stateData';
export default {
  components: {
    tableColumn
  },
  props: {
    // 操作那一列显示？ 联合 showDetailView
    showOperator: {
      type: Boolean,
      default: false
    },
    // 表格的数据
    tableData: {
      type: Array,
      required: true
    },
    // 表格列固定
    fixedKeyLeft: {
      type: Array,
      required: true
    },
    // 多级表头的数据
    tableHeader: {
      type: Array,
      required: true
    },
    // 表格的高度
    height: {
      type: String,
      default: '600'
    },
    tableTitle: {
      type: String,
      default: ''
    },
    tableLoading: {
      type: Boolean,
      required: true
    },
    isBorder: {
      type: Boolean,
      required: true
    },
    isStripe: {
      type: Boolean,
      required: false
    },

    isCanEdit: {
      type: Boolean,
      required: false
    }
  },

  data() {
    return {
      baseWidthVariable: commonVariable.baseWidthVariable,
      nameDisabled: false,
      tableHeight: ''
    };
  },
  watch: {
    isCanEdit: {
      handler: function() {
        this.$refs.xTable.refreshColumn();
      }
    }
  },
  mounted() {
    setTimeout(() => {
      this.tableHeight =
        window.innerHeight - this.$refs.xTable.$el.offsetTop - 160;
    }, 500);
  },
  methods: {
    // 显示查看明细列 ?
    showDetailView() {
      return this.showOperator && showDetailViewArr.includes(this.tableTitle);
    },
    viewClick(row) {
      this.$emit('viewClick', row);
    },
    getColumnWidth(col) {
      const matchRes = expandColunms.find(item => {
        return item.key === col.value;
      });
      return matchRes && matchRes.width || this.baseWidthVariable;
    },

    cellStyle({ column }) {
      const cellStyle = {
        'text-align': 'center'
      };
      const roleName = localStorage.getItem('xcRoleName');
      if (this.tableTitle === '按指标类型查询表' && roleName.indexOf('财政') !== -1) {
        if (/IMONEY/g.test(column.property)) {
          cellStyle['text-align'] = 'right';
        }
      } else {
        if (column.property !== 'CFUNCTIONCODE' && column.property !== 'CNAME' && column.property !== 'CENTERPRISECODE' && column.property !== 'CENTERPRISENAME' && column.property !== 'CNAME1' && column.property !== 'ENTERPRISENAME' && column.property !== 'IID') {
          cellStyle['text-align'] = 'right';
        }

        if (column.fixed === 'left') {
          cellStyle.backgroundColor = '#E6F7FF';
        }
      }
      return cellStyle;
    },
    footerCellClassName({ $rowIndex, column, columnIndex }) {
      if (column.property !== 'CENTERPRISECODE' && column.property !== 'CENTERPRISENAME' && column.property !== 'CNAME1' && column.property !== 'ENTERPRISENAME' && column.property !== 'IID') {
        return 'footer-col-right';
      }
    },
    getFixed(item) {
      if (this.fixedKeyLeft.includes(item.field)) {
        return 'left';
      } else {
        return '';
      }
    },
    editRowEvent(row) {
      this.$refs.xTable.setActiveRow(row);
    },
    saveRowEvent(row) {
      this.$refs.xTable.clearActived().then(() => {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.$XModal.message({ message: '保存成功！', status: 'success' });
        }, 300);
      });
    },

    footerMethod({ columns, data }) {
      // 需要后台给字段判断是否需要合计
      const footerData = [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '合计';
          } else {
            const roleName = localStorage.getItem('xcRoleName');
            if (this.tableTitle === '按指标类型查询表') {
              if (roleName.indexOf('乡镇') !== -1 && (columnIndex > 1) && (column.property !== 'do')) {
                return XEUtils.sum(data, column.property);
              } else {
                if (roleName.indexOf('财政') !== -1 && (columnIndex >= 10)) {
                  return XEUtils.sum(data, column.property);
                }
              }
            }
            if (/IMONEY/g.test(column.property)) {
              return XEUtils.sum(data, column.property);
            } else {
              return '--';
            }
          }
        })
      ];
      return footerData;
    }
  }
};
</script>
<style scoped lang='scss'>
.spanHover:hover {
  text-decoration: underline;
  cursor: pointer;
}
.dymamicTable_canedit {
  display: grid;
  grid-template-columns: 14px auto;
}
.dymamicTable_canedit__icon {
  opacity: 0;
  margin-right: 10px;
}
.dymamicTable_canedit__icon_show {
  opacity: 1;
}
>>> * {
  .summry-row {
    height: 35px;
    text-align: center;
    background-color: #E6F7FF;
    font-weight: 600;
  }
  .col--dirty {
    color: red;
    &::before {
      display: none;
    }
  }
}
.view-click {
  color: #1890FF;
  cursor: pointer;
  display: inline-block;
  text-align: center;
  width: 100%;
}
#dymamicTable /deep/ .vxe-table .vxe-body--column.col--ellipsis, .vxe-table.vxe-editable .vxe-body--column, .vxe-table .vxe-footer--column.col--ellipsis, .vxe-table .vxe-header--column.col--ellipsis {
    height: 30px !important;
}
</style>
